<template>
  <div>
    <!--文件上传选择按钮-->
    <el-upload
      :multiple="false"
      :before-upload="beforeUpload"
      :limit="1"
      :on-exceed="onExceed"
      :on-success="onSuccess"
      :file-list="fileList"
      :on-error="onError"
      class="upload-demo"
      drag
      action="/global/upImage"
      accept="image"
    >
      <i class="el-icon-upload"/>
      <div class="el-upload__text">将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
    </el-upload>
  </div>
</template>

<script lang="ts">
import Config from "@/config/index";
import WPopView from '@/utils/popView'
import { Component, Vue } from "vue-property-decorator";

@Component({})
export default class WebToolComUpImage extends Vue {
  // 文件列表
  fileList: File[] = [];

  // 文件上传前
  beforeUpload(file: File) {
    // 获取文件后缀名
    const suffixStr = file.name.split(".").pop();
    if (
      suffixStr &&
      (suffixStr === "jpg" ||
        suffixStr === "png" ||
        suffixStr === "JPG" ||
        suffixStr === "PNG" ||
        suffixStr === "JPEG" ||
        suffixStr === "jpeg")
    ) {
      const fileSize = file.size / 1024 / 1024;
      if (fileSize < 2) {
        return 1;
      }
      WPopView.msgError("最大支持2M");
    } else {
      WPopView.msgError("png、jpg、jpeg,格式");
    }
    return false;
  }
  // 文件个数超出限制
  onExceed() {
    WPopView.msgError("文件个数超出限制请，删除文件后重新上传");
  }
  // 文件上传成功后调用
  onSuccess(data: { code: number, data: any }) {
    if (data.code === 0) {
      this.$emit("upFinish", data.data);
      WPopView.msgSuccess("图片上传成功");
    } else {
      this.$emit("upFinish", "");
      WPopView.msgError("图片上传失败");
    }
  }
  // 文件上传失败后调用
  onError() {
    WPopView.msgError("图片上传失败");
  }
  clearFile() {
    this.fileList = [];
  }
}
</script>

<style scoped>
</style>
